package com.hrserviceserve.controller;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.id.NanoId;
import cn.hutool.http.server.HttpServerRequest;
import com.hrserviceserve.entity.Personnel;
import com.hrserviceserve.entity.Result;
import io.swagger.annotations.Api;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@Api(tags = "文件上传")
public class ImgController {
    @RequestMapping ("/imgUpload")
    public String upload(@RequestParam("file")MultipartFile file, HttpServletRequest request) throws Exception{
        String fileName=file.getOriginalFilename();//文件原始ming
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//后缀
        fileName=NanoId.randomNanoId(8)+suffixName;

//        String path= ResourceUtils.getURL("").getPath()+"static/";
        File file2 = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!file2.exists()) {
            file2 = new File("");
        }
        File upload = new File(file2.getAbsolutePath(),"static/images/");
        if(!upload.exists()) {
            upload.mkdirs();
        }
        String parent= upload.getPath();
        System.out.println(parent);
        File dir = new File(parent);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File dest = new File(dir, fileName);
        file.transferTo(dest);
        String path1="http://43.138.43.239:8090/images/";
        return path1+fileName;



//        ApplicationHome home = new ApplicationHome(getClass());
//        File jarFile = home.getSource();
//        String path = jarFile.getParentFile().getPath()+"/classes/public/img/";
//        File file1=new File(path);
//        if (!file1.exists()) {
//            file1.mkdirs();
//        }
//        System.out.println(path);
//        String path1="http://43.138.43.239:8090/logistics/";
//        System.out.println(path+fileName);
//        file.transferTo(new File(path+fileName));
//        return path1+fileName;
    }
    @PostMapping ("/header")
    public Result updateHeader(String id,MultipartFile file) throws IOException {
        System.out.println(id);

        Personnel personnel=new Personnel();
        String fileName=file.getOriginalFilename();//文件原始ming
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//后缀
        fileName= NanoId.randomNanoId(8)+suffixName;
        String path= ResourceUtils.getURL("classpath:").getPath()+"public/img/";
        file.transferTo(new File(path+fileName));
        System.out.println(path+fileName);
//        personnelService.save(personnel);
        return Result.success();
    }
}
